package com.onpositive.knowledge.model.values;

import java.util.ArrayList;
import java.util.IdentityHashMap;

import com.onpositive.semantic.model.api.command.CompositeCommand;
import com.onpositive.semantic.model.api.command.ICommand;
import com.onpositive.semantic.model.api.property.IProperty;
import com.onpositive.semantic.model.api.property.PropertyAccess;
import com.onpositive.semantic.model.api.property.ValueUtils;

public class ValueTransformOperation implements IObjectOperation{

	protected IValueTransformer transformer;
	protected IProperty pr;

	public ValueTransformOperation(IValueTransformer transformer, IProperty pr) {
		super();
		this.transformer = transformer;
		this.pr = pr;
	}

	public ICommand toCommand(Iterable<Object>... objcts) {
		CompositeCommand cm = new CompositeCommand();

		for (Object o : objcts) {
			Object value = pr.getValue(o);
			if (value != null) {
				Iterable<Object> collection = ValueUtils.toCollection(value);
				boolean hasAdjusts = false;
				IdentityHashMap<Object, Object> m = new IdentityHashMap<Object, Object>();
				for (Object oa : collection) {
					Object adjust = transformer.adjust(o, pr,
							(DescribedValue) value);
					if (adjust != null && adjust.equals(oa)) {
						hasAdjusts = true;
						m.put(oa, adjust);
					}
				}

				if (hasAdjusts) {
					ArrayList<Object> vls = new ArrayList<Object>();
					for (Object oa : collection) {
						if (m.containsKey(oa)) {
							vls.add(m.get(oa));
						} else {
							vls.add(oa);
						}
					}
					cm.addCommand(PropertyAccess.createSetValueCommand(vls, m,
							pr));
				}
			}
		}
		if (!cm.isEmpty()) {
			return cm;
		}
		return null;
	}

}
